<template>
  <div>
    <el-dialog v-bind="$attrs" width="800px" :show-close="false">
      <super-form
        ref="modalForm"
        label-width="100px"
        size="middle"
        form-ref="modalForm"
        :form-data="formData"
        :render-form-item="renderFormItem"
        :form-buttons="formButtons"
      />
      <el-form
        ref="ruleForm"
        :model="twoFormData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="业务范围" prop="underdeptNames">
          <el-input
            v-model="twoFormData.underdeptNames"
            size="small"
            placeholder="请点击右侧图标选择部门"
            :disabled="true"
            style="width: 627px"
          >
            <el-button
              slot="append"
              icon="el-icon-s-tools"
              @click="handleBusinessButton"
            />
          </el-input>
        </el-form-item>
        <el-form-item label="指标权限" prop="dataRightType">
          <el-radio
            v-model="twoFormData.dataRightType"
            :label="1"
            :disabled="indicatorDisabled"
            @change="changeDataRightType"
          >
            全部数据
          </el-radio>
          <el-radio
            v-model="twoFormData.dataRightType"
            :label="2"
            :disabled="indicatorDisabled"
            @change="changeDataRightType"
          >
            指定范围
          </el-radio>
        </el-form-item>
      </el-form>

      <el-card class="card">
        <el-tree
          ref="tree"
          :data="treeDataC"
          show-checkbox
          node-key="id"
          :props="defaultProps"
          highlight-current
          default-expand-all
          :default-checked-keys="allCheckedTreeId"
          @check-change="handleCheckChange"
        />
      </el-card>
      <el-dialog
        width="500px"
        :title="'选择' + innerTitle"
        :visible="innerVisible"
        :show-close="false"
        append-to-body
      >
        <div class="scopeSelect">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAll"
          >
            {{ innerTitle + '列表' }}
          </el-checkbox>
          <el-checkbox-group v-model="checkedName" @change="handleChecked">
            <el-checkbox
              v-for="item in innerOptions"
              :key="item.key"
              :label="item.value"
            >
              {{ item.value }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" size="small" @click="handleInnerConfirmU">
            确 认
          </el-button>
          <el-button type="info" size="small" @click="handleCancle">
            取 消
          </el-button>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import SuperForm from '@/components/SuperForm'
import { updateFormItem } from './config'
import {
  selectDutyList,
  selectOrgList,
  selectDeptList
} from '@/api/common/commonDropDown'
import { getDeptKpiTree, getProAreaKpiTree } from '@/api/commonDropDown'
import { transTreeData } from '@/utils/index'

export default {
  name: 'DeviceUpdate',
  components: { SuperForm },
  props: {
    deviceCodeDisabled: {
      type: Boolean,
      default: false
    },
    formData: {
      type: Object,
      default: () => ({})
    },
    handleSubmitF: {
      type: Function,
      default: () => {}
    }
  },
  data() {
    return {
      twoFormData: { underdeptNames: '', dataRightType: '' },
      indicatorDisabled: true,
      rules: {
        underdeptNames: [{ required: true, message: '请选择部门' }],
        dataRightType: [
          { required: true, message: '请勾选指标', trigger: 'change' }
        ]
      },
      // treeData: [],
      renderFormItem: [],
      formButtons: {
        isDialog: true,
        submitName: '提交',
        resetName: '取消',
        submitCallback: values => this.handleSubmit(values),
        resetCallback: () => this.handleCancleF()
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      treeDataC: [], // 部门树数据
      sourceTree: [],
      allCheckedTreeId: [],
      checkedTreeNode: [],
      accountTypeValue: 0, // 所在地key
      innerVisible: false,
      innerTitle: '添加',
      checkAll: false, // 内部弹窗的操作数据 start
      checkedName: [],
      checkedId: [],
      outId: [],
      outName: [],
      innerOptions: [],
      isIndeterminate: false, // end
      dataRightTypeDisabled: true,
      kpiTree: [],
      addOrEdit: true //  true 新增
    }
  },
  watch: {
    dataRightTypeDisabled: {
      handler: function() {
        if (!this.accountTypeValue) {
          this.dataRightTypeDisabled = true
        }
        this.renderFormItem = updateFormItem(
          this.changeLocation,
          // this.changeDataRightType,
          this.handleBusinessScope,
          this.dataRightTypeDisabled,
          this.passwordFocus
        )
      },
      immediate: true
    },
    formData: {
      handler() {
        this.formatFormData()
      },
      immediate: true
    }
  },
  mounted() {
    this.formatDropDown()
  },
  methods: {
    // 提交
    handleSubmit(values) {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (this.checkedTreeNode.length === 0) {
            this.$message({
              message: '请勾选指标权限',
              type: 'warning'
            })
            return
          }
          var settingList = []
          this.checkedTreeNode.forEach(obj => {
            if (obj.type === 6) {
              settingList.push({
                dataObjectId: parseInt(obj.id),
                dataObjectName: obj.label
              })
            }
          })
          this.handleSubmitF(
            {
              ...values,
              underdeptIds: this.outId.join(),
              // underdeptNames: this.outName.join(),
              dataRightType: this.twoFormData.dataRightType,
              underdeptNames: this.twoFormData.underdeptNames,
              dataRightSettingList: settingList
            },
            { addOrEdit: this.addOrEdit }
          )
          this.clearData()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // handleBusinessButton() {
    //   console.log('业务范围点击')
    // },
    // 点击取消
    handleCancleF() {
      this.$emit('update:visible', false)
      this.clearData()
    },
    // 改变所在地
    changeLocation(e, data = { addOrEdit: true }) {
      if (!(this.$refs.modalForm === undefined)) {
        delete this.$refs.modalForm.normalizedFormData.deptId
        this.$refs.modalForm.normalizedFormData.dataRightType = 2
        this.twoFormData.underdeptNames = ''
        this.twoFormData.dataRightType = 2
        this.checkedName = []
        this.allCheckedTreeId = []
      }
      this.checkedTreeNode = []
      // 指标权限让选择
      this.dataRightTypeDisabled = false
      this.indicatorDisabled = false
      this.twoFormData.underdeptNames = data.underdeptNames
      this.twoFormData.dataRightType = data.dataRightType
      // 改变所在地
      this.accountTypeValue = e
      if (e === 1) {
        this.GetDeptUserTree(false, data)
      } else {
        this.getProAreaKpiTree(false, data)
      }
      // 部门下拉
      selectDeptList({ type: this.accountTypeValue }).then(val => {
        const res = val.map(e => ({ key: e.id, value: e.name }))
        this.innerOptions = res
        this.renderFormItem.forEach(obj => {
          for (const key in obj) {
            if (obj[key] === 'deptId') {
              this.$set(obj.slotAttrs, 'options', res)
            }
          }
        })
      })
    },

    // 改变指标权限
    changeDataRightType(e) {
      if (e === 1) {
        this.sourceTree.forEach(e => {
          this.allCheckedTreeId.push(e.id)
        })
        const aa = transTreeData({
          list: this.sourceTree,
          rootId: '0',
          props: { pidKey: 'parentId' },
          appends: [
            { in: 'name', out: 'label' },
            { out: 'disabled', value: true }
          ]
        })
        this.treeDataC = aa
      } else {
        this.$refs.tree.setCheckedKeys([])
        const aa = transTreeData({
          list: this.sourceTree,
          rootId: '0',
          props: { pidKey: 'parentId' },
          appends: [
            { in: 'name', out: 'label' },
            { out: 'disabled', value: false }
          ]
        })
        this.treeDataC = aa
      }
    },

    // 业务范围右侧按钮点击
    handleBusinessButton() {
      if (this.accountTypeValue === 0) {
        this.$message({
          message: '请选选择所在地，再操作',
          type: 'warning'
        })
        return
      }
      if (this.accountTypeValue === 1) {
        this.innerTitle = '总部'
      } else if (this.accountTypeValue === 2) {
        this.innerTitle = '区域'
      } else {
        this.innerTitle = '项目'
      }
      this._setInnerModalData(this.innerTitle, true, {})
    },

    // 点击内部弹窗的确认
    handleInnerConfirmU() {
      this.outId = this.checkedId
      this.outName = this.checkedName
      this.twoFormData.underdeptNames = this.checkedName.join(',')
      this.innerVisible = false
    },
    // 点击内部弹窗的取消
    handleCancle() {
      this.innerVisible = false
    },

    // 获取总部 树数据
    GetDeptUserTree(flag = false, data = { addOrEdit: true }) {
      getDeptKpiTree({ deptType: this.accountTypeValue }).then(treeValue => {
        const aa = transTreeData({
          list: treeValue,
          rootId: '0',
          props: { pidKey: 'parentId' },
          appends: [{ in: 'name', out: 'label' }],
          disabled: flag
        })
        this.sourceTree = treeValue
        // 处理树形结构数据 end
        this.treeDataC = aa
        if (data.addOrEdit === true) {
          console.log(data.addOrEdit)
          return
        }
        // 处理选中
        this.$nextTick(() => {
          this.outId = data.underdeptIds.split(',')
          this.outName = data.underdeptNames.split(',')
          this.checkedId = data.underdeptIds.split(',')
          this.checkedName = data.underdeptNames.split(',')
          if (data.dataRightType === 1) {
            this.sourceTree.forEach(item => {
              this.allCheckedTreeId.push(item.id)
            })
            this.$refs.tree.setCheckedKeys(this.allCheckedTreeId)
            const aa = transTreeData({
              list: this.sourceTree,
              rootId: '0',
              props: { pidKey: 'parentId' },
              appends: [
                { in: 'name', out: 'label' },
                { out: 'disabled', value: true }
              ]
            })
            this.treeDataC = aa
          } else {
            data.dataRightSettingList.forEach(e => {
              this.sourceTree.forEach(item => {
                if (parseInt(item.id) === e.dataObjectId) {
                  this.checkedTreeNode.push({
                    id: item.id,
                    label: e.dataObjectName
                  })
                  this.$refs.tree.setCheckedNodes(this.checkedTreeNode)
                }
              })
            })
          }
        })
        // 非选中时
        if (!flag) {
          this.allCheckedTreeId = []
        }
      })
    },
    // 获取项目区域 树数据
    getProAreaKpiTree(flag = false, data = { addOrEdit: true }) {
      getProAreaKpiTree({ deptType: this.accountTypeValue }).then(treeValue => {
        this.sourceTree = treeValue
        const aa = transTreeData({
          list: treeValue,
          rootId: '0',
          props: { pidKey: 'parentId' },
          appends: [{ in: 'name', out: 'label' }]
        })
        // 处理树形结构数据 end
        this.treeDataC = aa
        if (data.addOrEdit === true) {
          return
        }
        // 处理选中
        this.$nextTick(() => {
          this.outId = data.underdeptIds.split(',')
          this.outName = data.underdeptNames.split(',')
          this.checkedId = data.underdeptIds.split(',')
          this.checkedName = data.underdeptNames.split(',')
          if (!data.addOrEdit) {
            if (data.dataRightType === 1) {
              this.sourceTree.forEach(item => {
                this.allCheckedTreeId.push(item.id)
              })
              this.$refs.tree.setCheckedKeys(this.allCheckedTreeId)
              const aa = transTreeData({
                list: this.sourceTree,
                rootId: '0',
                props: { pidKey: 'parentId' },
                appends: [
                  { in: 'name', out: 'label' },
                  { out: 'disabled', value: true }
                ]
              })
              this.treeDataC = aa
            } else {
              data.dataRightSettingList.forEach(e => {
                this.sourceTree.forEach(item => {
                  if (parseInt(item.id) === e.dataObjectId) {
                    this.checkedTreeNode.push({
                      id: item.id,
                      label: e.dataObjectName
                    })
                    this.$refs.tree.setCheckedNodes(this.checkedTreeNode)
                  }
                })
              })
            }
          }
        })
        // 非选中时
        if (!flag) {
          this.allCheckedTreeId = []
        }
      })
    },
    // 职务下拉
    // 机构下拉
    formatDropDown() {
      selectDutyList({}).then(val => {
        const res = val.map(e => ({ key: e.id, value: e.name }))
        this.renderFormItem.forEach(obj => {
          for (const key in obj) {
            if (obj[key] === 'dutyId') {
              this.$set(obj.slotAttrs, 'options', res)
            }
          }
        })
      })

      selectOrgList({}).then(val => {
        const res = val.map(e => ({ key: e.id, value: e.name }))
        this.renderFormItem.forEach(obj => {
          for (const key in obj) {
            if (obj[key] === 'orgId') {
              this.$set(obj.slotAttrs, 'options', res)
            }
          }
        })
      })
    },
    _setInnerModalData(title = '添加账号', visible = true, formData = {}) {
      // 设置弹窗
      // this.innerModalFormData = formData
      this.innerTitle = title
      this.innerVisible = visible
      // this.deviceCodeDisabled = title !== '添加'
    },

    // 多选框处理 start
    handleCheckAll(val) {
      if (val) {
        this.innerOptions.forEach(e => {
          this.checkedId.push(e.key)
          this.checkedName.push(e.value)
        })
      } else {
        this.checkedId = []
        this.checkedName = []
      }
      this.isIndeterminate = false
    },
    handleChecked(value) {
      // 只拿到了name，还要拿id
      this.checkedId = []
      value.forEach(e => {
        this.innerOptions.forEach(item => {
          if (item.value === e) {
            this.checkedId.push(item.key)
          }
        })
      })
      const checkedCount = value.length
      this.checkAll = checkedCount === this.innerOptions.length
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.innerOptions.length
    },
    // 多选框处理 end

    // 树 被勾选
    handleCheckChange(e) {
      this.allCheckedTreeId = this.$refs.tree.getCheckedKeys()
      this.checkedTreeNode = this.$refs.tree.getCheckedNodes()
    },
    // 密码
    passwordFocus(val) {
      if (val !== this.formData.password) {
        this.$set(this.formData, 'password', '')
      }
    },
    // 设置节点选中
    // 数据渲染
    formatFormData() {
      if (this.formData.phone === undefined) {
        return
      }
      this.addOrEdit = false
      const {
        underdeptIds,
        underdeptNames,
        dataRightSettingList,
        accountType,
        dataRightType
      } = this.formData
      this.accountTypeValue = accountType
      this.changeLocation(accountType, {
        underdeptIds,
        underdeptNames,
        dataRightSettingList,
        dataRightType,
        addOrEdit: false
      })
    },
    // 清空数据
    clearData() {
      this.accountTypeValue = 0
      this.allCheckedTreeId = []
      this.checkedId = []
      this.checkedName = []
      this.checkedTreeNode = []
      this.innerOptions = []
      this.treeDataC = []
      this.dataRightTypeDisabled = true
      this.addOrEdit = true
      this.twoFormData.underdeptNames = ''
      this.twoFormData.dataRightType = 0
      this.indicatorDisabled = true
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/ .el-dialog__header {
  border-bottom: 1px solid #eaeaea;
}
/deep/ .el-card.is-always-shadow {
  box-shadow: none;
}
/deep/ .el-dialog {
  margin-top: 5vh !important;
}
/deep/.empty-block {
  height: 0px;
}
.el-checkbox {
  display: block;
}
/deep/ .el-checkbox__label {
  color: #333 !important;
  font-size: 13px;
  font-weight: 400;
}
/deep/ label {
  font-weight: 400;
}
/deep/ .el-form-item {
  margin-bottom: 18px;
}
/deep/ .el-dialog__body {
  position: relative;
}
.dialog-footer {
  text-align: center;
}

.card {
  width: 625px;
  height: 300px;
  margin-top: 54px;
  margin-left: 100px;
  margin-bottom: 15px;
  transform: translateY(-35px);
  overflow: auto;
}
.scopeSelect {
  margin-left: 65px;
  width: 260px;
  max-height: 500px;
  overflow-y: auto;
  border: 1px solid #ccc;
  border-radius: 4px;
  // position: relative;
  background-color: #fff;
  z-index: 10;
  > .el-checkbox {
    width: 255px;
    position: absolute;
    top: 31px;
    left: 86px;
    border-bottom: 1px solid #ccc;
    height: 38px;
    line-height: 38px;
    margin-left: 0px;
    padding-left: 15px;
    background-color: #fff;
    z-index: 3;
    /deep/.el-checkbox__label {
      margin-left: 130px;
    }
  }
}
.el-checkbox {
  height: 34px;
  line-height: 34px;
  margin-left: 15px;
  border-radius: 4px 4px 0 0;
}
.el-checkbox-group {
  margin-top: 38px;
  > .el-checkbox {
    border: none;
  }
}
</style>
